<?php

namespace Api\Controller;

use Think\Controller;

class CommonController extends Controller\RestController {

    protected $returnData;
    protected $redis;

    public function _initialize() {

        header("Access-Control-Allow-Origin:*");
        header('Access-Control-Allow-Headers: X-Requested-With,SIGN');

        if($this->_method !== 'post') {
            $data['errorCode']=C('ERROR_CODE.ERROR_METHOD');
            $data['errorMsg']=C('ERROR_MSG.ERROR_METHOD');
            $this->response($data,'json');
            exit();
        }

        $this->returnData['errorCode'] = 200;
        $this->returnData['msg'] = '';

    }

    //错误返回
    function errorReturn($errorEnum) {
        $this->returnData['errorCode'] = C('ERROR_CODE.' . $errorEnum);
        $this->returnData['errorMsg'] = C('ERROR_MSG.' . $errorEnum);
        $this->response($this->returnData, 'json');
        exit();
    }

    //加密手机验证码
    public function authMobileCode($str) {
        $key = substr(md5(C('SMS_AUTH_KEY')), 5, 8);
        $str = substr(md5($str), 8, 10);
        return md5($key . $str);
    }

    //发送短信验证码
    public function sendMobileCode() {

        $mobile = I('post.mobile');

        $code = rand(1000,9999);

        mms(C('mmskey'), $mobile, "验证码为：".$code."请在5分钟之内输入");

        //保存手机验证码
        $key = $this->authMobileCode(C('SMS_AUTH_KEY'));
        $mobile = $this->authMobileCode($mobile);
        $code = $this->authMobileCode($code);

        S($key.$mobile, $code, intval(C('SMS_EXPIRE_TIME')));

        $this->response($this->returnData, 'json');

    }

    //校验短信验证码
    public function checkMobileCode($mobile, $code) {

        $mobile = $this->authMobileCode($mobile);
        $key = $this->authMobileCode(C('SMS_AUTH_KEY')).$mobile;

        //获取验证码
        $seCode = S($key);

        //判断验证码是否存在
        if(isNullOrEmpty($code)) {
            return false;
        }

        //判断验证码是否正确
        if($this->authMobileCode($code) == $seCode) {
            S($key, null);
            return true;
        }

        return false;

    }

    //上传图片（base64）
    function uploadImage() {

        $xmlstr = $GLOBALS['HTTP_RAW_POST_DATA'];
        if (empty($xmlstr))
            $xmlstr = file_get_contents('php://input');

        $arr = explode('&', $xmlstr);

        $fileStreamStr = $arr[0];

        $fileStreamArr = explode('=', $fileStreamStr);

        $fileStream = base64_decode(rawurldecode($fileStreamArr[1]));

        $targetFolder = '/Uploads/'; // Relative to the root

        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;

        $filename = md5(time()) . '.jpg'; //要生成的图片名字

        $targetFile = rtrim($targetPath, '/') . '/' . $filename;

        $image = $fileStream; //得到post过来的二进制原始数据
        $file = fopen($targetPath . $filename, "w"); //打开文件准备写入
        fwrite($file, $image); //写入
        fclose($file); //关闭

        $imgUrl = '.' . $targetFolder . $filename;

        $thinkImage = new \Think\Image();
        $thinkImage->open($imgUrl);

        $imagePath = '.' . $targetFolder . 'thumb_' . $filename;

        $thinkImage->thumb(300, 300, \Think\Image::IMAGE_THUMB_CENTER)->save($imagePath);

        $this->returnData['data'] = C('rooturl') . $targetFolder . 'thumb_' . $filename;

        echo json_encode($this->returnData);
    }

    //计算秒间隔
    public function calculateSecondGap($from, $to) {
        $min = ceil(strtotime($to) - strtotime($from));
        return $min;
    }

    //计算分钟间隔
    public function calculateMinGap($from, $to) {
        $min = ceil($to - $from) / 60;
        return $min;
    }

    /**
     * @desc 根据两点间的经纬度计算距离 
     * @param float $lat 纬度值 
     * @param float $lng 经度值 
     */
    function getDistance($lat1, $lng1, $lat2, $lng2) {

        $earthRadius = 6367000; //approximate radius of earth in meters 

        /*
          Convert these degrees to radians
          to work with the formula
         */

        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;

        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        /*
          Using the
          Haversine formula

          http://en.wikipedia.org/wiki/Haversine_formula

          calculate the distance
         */

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);  //这个计算结果单位是M
    }

    public function guid() {

        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45); // "-"
            $uuid = //chr(123)// "{"
                    substr($charid, 0, 8) . $hyphen
                    . substr($charid, 8, 4) . $hyphen
                    . substr($charid, 12, 4) . $hyphen
                    . substr($charid, 16, 4) . $hyphen
                    . substr($charid, 20, 12);
            //.chr(125);// "}"
            return $uuid;
        }
    }
}
